/** Concrete implementation Repository for Session objects
 *
 *  @author Scott Monahan
 *  @version $Id$
 *  
 *  File last changed on $Date:$ by $Author:$ in $Rev:$
 *
 */

package info637.pprc.repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import info637.pprc.model.Session;

@Component(value = "sessionRepository")
public class SessionRepository extends AbstractListBasedRepository<Session, SessionFilter> 
	implements ISessionRepository {

	static Logger log = Logger.getLogger(SessionRepository.class.getName());
	
	@Override
	public Session createNewSession() {
		
		Session out = null;
		
		synchronized(this) {
			
			out = new Session(Long.toString(System.currentTimeMillis()));
			
			this.add(out);
		}
		
		return out;
	}

	@Override
	public Session findBySessionId(String sessionId) {

		List<Session> sessionList = this.fetch(new SessionFilter(sessionId));
		
		if (sessionList != null && sessionList.size() > 0) {
			
			return this.fetch(new SessionFilter(sessionId)).get(0);
			
		} else {
			
			return null;
		}
	}

	@Override
	public void updateLastAccessed(Session session) {
		
		this.update(session, new Session(session.getId(), session.getSessionId()));
	}

	@Override
	public List<String> expireSessions(int timeoutInMills) {

		List<String> expiredSessions = new ArrayList<String>();
		
		List<Session> allSessions = this.fetchAll();
		
		for (Session session : allSessions) {
			
			log.debug("Checking Session ID: [" + session.getSessionId() + "]");
			
			Date expireDate = new Date(System.currentTimeMillis() -  (timeoutInMills + 1));
			
			log.debug("Last Accessed: [" + session.getLastAccessed().toString() + "]");
			log.debug("Expire Time: [" + expireDate.toString() + "]");
			
			if(session.getLastAccessed().before(expireDate)) {
				
				expiredSessions.add(session.getSessionId());
				
				this.delete(session);
			}
		}
		
		return expiredSessions;
	}
}
